import React, { useContext, useMemo, useRef, useState } from 'react';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import { ReplyContext } from './context';
import styles from './index.less';

const ReplyItem: React.FC<Reply.ItemProps> = (props) => {
  const { type, placeholder } = props;
  const { reply, setReply, updateInputValue } = useContext(ReplyContext);
  const [value, setValue] = useState<string>('');
  const currentRef = useRef();

  useMemo(() => {
    if (currentRef.current) {
      currentRef.current.getEditor().root.dataset.placeholder = placeholder;
    }
  }, [placeholder]);

  useMemo(() => {
    if (Object.keys(updateInputValue).length) {
      setValue(updateInputValue[type]);
    }
  }, [updateInputValue]);

  useMemo(() => {
    if (currentRef.current) {
      const content = currentRef.current.getEditor().getText().replace(/\s/g, '');
      const obj = {};
      obj[type] = content;
      setReply({ ...reply, ...obj });
    }
  }, [value]);

  return (
    <ReactQuill
      ref={currentRef}
      value={value}
      placeholder={placeholder}
      modules={{ toolbar: null }}
      theme="snow"
      className={styles['input-box']}
      onChange={setValue}
      style={{ borderRadius: 4 }}
    />
  );
};

export default ReplyItem;
